package com.joven.shelltest.controller;

import com.joven.shelltest.model.Result;
import com.joven.shelltest.model.SuccessKilled;
import com.joven.shelltest.utils.disruptor.DisruptorUtil;
import com.joven.shelltest.utils.disruptor.SecondKillEvent;
import com.joven.shelltest.utils.seondkill.SecondKillQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @Author wzj
 * @Date 2023-08-15 10:29
 **/
@Slf4j
@RestController
@RequestMapping("/secKill")
public class SecKillController {

    @PostMapping("/start/queue")
    public Result startQueue(long skgId){
        try {
            log.info("开始秒杀方式自定义队列...");
            final long userId = (int) (new Random().nextDouble() * (99999 - 10000 + 1)) + 10000;
            SuccessKilled kill = new SuccessKilled();
            kill.setSecKillId(skgId);
            kill.setUserId(userId);
            Boolean flag = SecondKillQueue.getSkillQueue().produce(kill);
            // 虽然进入了队列，但是不一定能秒杀成功 进队出队有时间间隙
            if(flag){
                log.info("用户:{}{}",kill.getUserId(),"秒杀成功");
            }else{
                log.info("用户:{}{}",userId,"秒杀失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }


    @PostMapping("/start/disruptor")
    public Result startDisruptor(long skgId){
        try {
            log.info("开始秒杀方式disruptor...");
            final long userId = (int) (new Random().nextDouble() * (99999 - 10000 + 1)) + 10000;
            SecondKillEvent kill = new SecondKillEvent();
            kill.setSecKillId(skgId);
            kill.setUserId(userId);
            DisruptorUtil.producer(kill);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }
}
